import {IState, IAction, ACTION_TYPE, ITodo} from './typings';

export const todoReducer = (state: IState, action: IAction) => {
    const {type, payload} = action;
    switch (type){
        case ACTION_TYPE.ADD_TODO:
            return {
                ...state,
                todoList: [...state.todoList, payload as ITodo]
            }
        case ACTION_TYPE.REMOVE_TODO:
            return {
                ...state,
                todoList: state.todoList.filter(item => item.id !== payload) 
            }
        case ACTION_TYPE.TOGGLE_TODO:
            return {
                ...state,
                todoList: state.todoList.map(todo => {
                    return todo.id === payload ? {
                        ...todo,
                        completed: todo.completed
                    } : {
                        ...todo
                    }
                })
            }
        default:
            return state
    }
}